;(function(){
  'use strict';
  angular.module('controllers.resourcesWatchData.netDevInfoView',[])
    .controller('netDevInfoCtrl',netDevInfoCtrl)
    .controller('netDevInfoDetailCtrl',netDevInfoDetailCtrl);

  function netDevInfoCtrl($scope,NetDevInfoViewServer,ResourceTypes,CoreService,$state,$cookies){
    $scope.toggle = {
      isFolded:true
    };
    $scope.netDevInfo = {};
    $scope.selector = {
      resourceType : ResourceTypes
    };
    $scope.pageObj = {
      currentPage : 1,
      pageSize : '10'
    };
    $scope.netDevQuery = function(){
      var param = {};
      if($scope.toggle.isFolded){
        param = setParam();
        NetDevInfoViewServer.netDevQuery(param,function(res){
          if(res.state !== '10000' || is.not.array(res.data) || res.data.length === 0){
            CoreService.dialog(res.state);
            return;
          }
          $scope.pageObj.param = param;
          $scope.pageObj.param.page = {
            currentPage : 1,pageSize:'10'
          };
          $scope.pageObj.totalCount = res.data.length;
          setSeries(res.data,$scope.pageObj.currentPage,$scope.pageObj.pageSize);
          $scope.toggle.isFolded = !$scope.toggle.isFolded;
          $scope.isQuery = true;
        });
      }else{
        $scope.toggle.isFolded = !$scope.toggle.isFolded;
      }
    };
    $scope.getDevDetail = function(item){
      $cookies.putObject('device',item);
      $state.go('sas.resourcesWatchData.netDevInfoDetail');
    };

    $scope.turnToPage = function(param){
      var tempParam = {
        moduleCode : param.moduleCode
      };
      NetDevInfoViewServer.netDevQuery(tempParam,function(res){
        if(res.state!=='10000' || is.not.array(res.data) || res.data.length === 0){
          CoreService.dialog(res.state);
          return;
        }
        $scope.pageObj.totalCount = res.data.length;
        setSeries(res.data,param.page.currentPage,param.page.pageSize);
      });
    }

    function setSeries(data,currentPage,pageSize){
      var begin = (Number(currentPage)-1)*Number(pageSize);
      var end = Number(currentPage)*Number(pageSize);
      $scope.series = [];
      for(;begin < end && begin < data.length;begin++){
        $scope.series.push(data[begin]);
      }
    }

    function setParam(){
      var tempParam = {
        moduleCode:''
      };
      if($scope.netDevInfo.resourceType){
        tempParam.moduleCode = $scope.netDevInfo.resourceType.moduleCode;
      }
      return tempParam;
    }
  }

  netDevInfoCtrl.$inject = ['$scope','NetDevInfoViewServer','ResourceTypes','CoreService','$state','$cookies'];

  function netDevInfoDetailCtrl($scope,COREDATA,NetDevInfoViewServer,$cookies,CoreService,$timeout){
    var now = new Date();
    var charts = {};
    var options = {};
    $scope.date = initDate('1');
    $scope.device = $cookies.getObject('device');
    $scope.toggle = {
      isFolded:true
    };
    $scope.selector = {
      timeType :[{
          timeTypeCode: '1',
          timeTypeName: '日'
        }, {
          timeTypeCode: '3',
          timeTypeName: '月'
        }]
    };
    $scope.netDevDetail = {
      quarter:{}
    };
    $scope.formatArr = [
      undefined,'yyyy-MM-dd',undefined,'yyyy-MM-01','yyyy-01-01','yyyy-01-01'
    ];

    $scope.$watch('netDevDetail.timeType',function(n,o){
      if(n === o) {
        return;
      }
      $scope.date = initDate(n.timeTypeCode);
    });

    $scope.$watch('date.startTime',function(n,o){
      if(n === o || n === null || n === undefined) return;
      if($scope.date.startTime >= $scope.date.endTime) return;
      if($scope.netDevDetail.timeType && $scope.netDevDetail.timeType.timeTypeCode === '3'){
        $scope.netDevDetailForm.monthEndTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.monthStartTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.monthEndTime.$setUntouched();
        $scope.netDevDetailForm.monthStartTime.$setUntouched();
        if(new Date(n.getTime()).setMonth(n.getMonth()+3) < $scope.date.endTime.getTime()){
          $scope.netDevDetailForm.monthStartTime.$setValidity('time-diff',false);
        }
      }else{
        $scope.netDevDetailForm.dateStartTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.dateEndTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.dateEndTime.$setUntouched();
        $scope.netDevDetailForm.dateStartTime.$setUntouched();
        if(new Date(n.getTime()).setDate(n.getDate()+3) < $scope.date.endTime.getTime()){
          $scope.netDevDetailForm.dateStartTime.$setValidity('time-diff',false);
        }
      }   
    },true);

    $scope.$watch('date.endTime',function(n,o){
      if(n === o || n === null || n === undefined) return;
      if($scope.date.startTime >= $scope.date.endTime) return;
      if($scope.netDevDetail.timeType && $scope.netDevDetail.timeType.timeTypeCode === '3'){
        $scope.netDevDetailForm.monthEndTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.monthStartTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.monthEndTime.$setUntouched();
        $scope.netDevDetailForm.monthStartTime.$setUntouched();
        if(new Date(n.getTime()).setMonth(n.getMonth()-3) > $scope.date.startTime.getTime()){
          $scope.netDevDetailForm.monthEndTime.$setValidity('time-diff',false);
        }
      }else{
        $scope.netDevDetailForm.dateStartTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.dateEndTime.$setValidity('time-diff',true);
        $scope.netDevDetailForm.dateEndTime.$setUntouched();
        $scope.netDevDetailForm.dateStartTime.$setUntouched();
        if(new Date(n.getTime()).setDate(n.getDate()-3) > $scope.date.startTime.getTime()){
          $scope.netDevDetailForm.dateEndTime.$setValidity('time-diff',false);
        }
      }  
    },true);

    function initDate(timeType){
      var date = {};
      var year = now.getFullYear();
      var month = now.getMonth();
      var day = now.getDate()-1;
      switch(timeType){
        case '3':
          date.startTime = new Date(year,month);
          date.endTime = new Date(year,month);
          break;
        case '5':
          date.startTime = year;
          date.endTime = year;
          break;
        default:
          date.startTime = new Date(year,month,day);
          date.endTime = new Date(year,month,day+1);
      }
      return date;
    }

    $scope.netDevInfoDetailQuery = function(){
      var param = {};
      var series = {};
      if($scope.toggle.isFolded){
        param = setParam();
        NetDevInfoViewServer.netDevInfoQuery(param,function(res){
          if(res.state !== '10000' || is.not.array(res.data) || checkData(res.data)){
            CoreService.dialog(res.state);
            return;
          }
          $scope.series = [];
          angular.forEach(res.data,function(item){
            series[item.deviceIp] = {
              'ip':item.deviceIp
            };
          });
          angular.forEach(series,function(item){
            $scope.series.push(item);
          });
          $timeout(function(){setCharts(param);},0);
          
        });
      }else{
        $scope.toggle.isFolded = !$scope.toggle.isFolded;
      }

      function checkData(data){
        var isNull = true;
        if(data && is.array(data) && data.length !== 0){
          // angular.forEach(data,function(item){
          //   if(is.array(item.useDetails) && item.useDetails.length !== 0){
              isNull = false;
          //   }
          // });
        }
        return isNull;
      }
    };

    function setParam(){
      var param = {};
      if($scope.netDevDetail.timeType){
        param.timeType = $scope.netDevDetail.timeType.timeTypeCode;
        var format = $scope.formatArr[$scope.netDevDetail.timeType.timeTypeCode];
        switch($scope.netDevDetail.timeType.timeTypeCode){
          case '4':
            param.startTime = $scope.netDevDetail.quarter.startTime.substr(0,4)+'-01-01';
            param.endTime = $scope.netDevDetail.quarter.endTime.substr(0,4)+'-01-01';
            param.startQuarter = $scope.netDevDetail.quarter.startTime.substr(4,1);
            param.endQuarter = $scope.netDevDetail.quarter.endTime.substr(4,1);
            break;
          case '5':
            param.startTime = $scope.date.startTime+'-01-01';
            param.endTime = $scope.date.endTime+'-01-01';
            break;
          default :
            param.startTime = CoreService.dateFormat($scope.date.startTime,format);
            param.endTime = CoreService.dateFormat($scope.date.endTime,format);
        }
      }else{
        param.timeType = $scope.selector.timeType[0].timeTypeCode;
        param.startTime = CoreService.dateFormat($scope.date.startTime,'yyyy-MM-dd');
        param.endTime = CoreService.dateFormat($scope.date.endTime,'yyyy-MM-dd');
      }
      param.moduleCode = $scope.device.moduleCode;
      return param;
    }

    function setCharts(param){
      angular.forEach($scope.series,function(item,key){
        charts['cpu'+key] = echarts.init(document.getElementById('devCpuChart'+key));
        charts['memory'+key] = echarts.init(document.getElementById('devMemoryChart'+key));
        charts['temp'+key] = echarts.init(document.getElementById('devTempChart'+key));
      });
      $timeout(function(){progressData(param);},0);
    }

    $scope.changeChart = function(ip){
      $scope.showIp = ip;
    }

    function progressData(param){
      var xAxisData = {},yAxisData = {};
      var timeDiff;
      var beginTime = new Date(param.startTime);
      var year = beginTime.getFullYear(),
          month = beginTime.getMonth(),
          day = beginTime.getDate();
      angular.forEach($scope.series,function(item,key){
        xAxisData['cpu'+key] = [];
        yAxisData['cpu'+key] = [];
        xAxisData['memory'+key] = [];
        yAxisData['memory'+key] = [];
        xAxisData['temp'+key] = [];
        yAxisData['temp'+key] = [];
        timeDiff = getTimeDiff(param);
        for(var i = 0;i < timeDiff;i++){
          xAxisData['cpu'+key].push(CoreService.dateFormat(new Date(year,month,day+i),'yyyy-MM-dd'));
          yAxisData['cpu'+key].push(Math.random()*15+5+Math.random()*40);
          xAxisData['memory'+key].push(CoreService.dateFormat(new Date(year,month,day+i),'yyyy-MM-dd'));
          yAxisData['memory'+key].push(Math.random()*15+5+Math.random()*40);
          xAxisData['temp'+key] .push(CoreService.dateFormat(new Date(year,month,day+i),'yyyy-MM-dd'));
          yAxisData['temp'+key] .push(Math.random()*15+35+Math.random()*10);
        }
        options['cpu'+key] = new ChartOpt('cpu',xAxisData['cpu'+key],'{value}%',yAxisData['cpu'+key]);
        options['memory'+key] = new ChartOpt('内存',xAxisData['memory'+key],'{value}%',yAxisData['memory'+key]);
        options['temp'+key] = new ChartOpt('温度',xAxisData['temp'+key],'{value}°C',yAxisData['temp'+key]);
        charts['cpu'+key].setOption(options['cpu'+key]);
        charts['memory'+key].setOption(options['memory'+key]);
        charts['temp'+key].setOption(options['temp'+key]);
      });
      $scope.showIp = $scope.series[0].ip;
      $scope.isQuery = true;
      $scope.toggle.isFolded = !$scope.toggle.isFolded;
    }

    function getTimeDiff(param){
      var timeDiff;
      timeDiff = new Date(param.endTime).getTime() - new Date(param.startTime).getTime();
      return (timeDiff / 86400000);
    }

    function ChartOpt(title,xAxisData,formatter,yAxisData){
      this.title = {
        text: title,
        x:'center'
      };
      this.xAxis = [
        {
          type : 'category',
          boundaryGap : true,
          data : xAxisData
        }
      ];
      this.animation = false;
      this.yAxis = [
        {
          type : 'value',
          axisLabel : {
            formatter: formatter
          }
        }
      ];
      this.series = [
        {
          name:'',
          type:'line',
          data:yAxisData,
          smooth:true,
          symbolSize:1
        }
      ];            
    }
  }

  netDevInfoDetailCtrl.$inject = ['$scope','COREDATA','NetDevInfoViewServer','$cookies','CoreService','$timeout'];
})();